package com.situ.web.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class UpdateStudentServlet
 */
@WebServlet("/updateStudent")
public class UpdateStudentServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//super.service(req, resp);
		//乱码问题
        req.setCharacterEncoding("utf-8");
		
		String id = req.getParameter("id");
		String name = req.getParameter("name");
		String age = req.getParameter("age");
		String gender = req.getParameter("gender");
		System.out.println("id: " + id);
		System.out.println("name: " + name);
		System.out.println("age: " + age);
		System.out.println("gender: " + gender);
		// 根据id来更新的操作
				Connection connection = null;
				PreparedStatement preparedStatement = null;
				try {
					connection = JDBCUtil.getConnection();
					String sql = "update student set name=?,age=?,gender=? where id=?";
					preparedStatement = connection.prepareStatement(sql);
					preparedStatement.setString(1, name);
					preparedStatement.setInt(2, Integer.parseInt(age));
					preparedStatement.setString(3, gender);
					preparedStatement.setInt(4, Integer.parseInt(id));
					int count = preparedStatement.executeUpdate();
					if (count == 1) {
						System.out.println("修改成功");
					} else {
						System.out.println("修改失败");
					}
				} catch (SQLException e) {
					e.printStackTrace();
				} finally {
					JDBCUtil.close(connection, preparedStatement, null);
				}
				// 修改完之后，重定向到/Java1912Web/findAllStudent
//				resp.sendRedirect("/Java1912Web/findAllStudent")
				resp.sendRedirect(req.getContextPath() + "/findAllStudent");
			
	}

}
